package com.miexiaoliang.springbootshiro.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.miexiaoliang.springbootshiro.User;

/**
 * 用户名+密码登录及授权，同理后续可添加手机号码+密码、邮箱+密码登录
 */
public class UserNameRealm extends AuthorizingRealm {

    /**
     * 授权，即用户权限判别
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        // 登录用户 id
        User user = (User) principalCollection.getPrimaryPrincipal();
        Integer userId = user.getId();

        // 获取角色、权限
        List<String> roleList = new ArrayList<>();
        List<String> permissionList = new ArrayList<>();
        permissionList.add("user:list");

        // 返回授权信息
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roleList);
        simpleAuthorizationInfo.addStringPermissions(permissionList);

        return simpleAuthorizationInfo;

    }

    /**
     * 认证，即用户登录
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        // 获取用户输入的用户名和密码
        String userName = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());

        // 这里的 user 实际情况是从 db 中通过 userName 查询获取
        User user = new User();
        user.setId((int) (System.currentTimeMillis() % 1000));
        user.setUserName(userName);
        user.setPassword("123456");

        if (null == user) {
            // 用户为空即用户不存在，抛异常
        }
        if (!password.equals(user.getPassword())) {
            throw new IncorrectCredentialsException("用户名或密码错误！");
        }
        // 用户被锁定，也有这种情况

        return new SimpleAuthenticationInfo(user, password, getName());

    }

}
